import { createRouter, createWebHistory, RouteRecordRaw } from 'vue-router'

// 定义路由元数据接口
interface RouteMeta {
  requiresAuth: boolean
}

// 定义路由记录类型
type AppRouteRecordRaw = RouteRecordRaw & {
  meta: RouteMeta
  children?: AppRouteRecordRaw[]
}

const routes: AppRouteRecordRaw[] = [
  {
    path: '/login',
    name: 'Login',
    component: () => import('../views/common/Login.vue'),
    meta: { requiresAuth: false }
  },
  {
    path: '/register',
    name: 'Register',
    component: () => import('../views/common/Register.vue'),
    meta: { requiresAuth: false }
  },
  {
    path: '/',
    component: () => import('../components/Layout.vue'),
    redirect: '/home',
    meta: { requiresAuth: true },
    children: [
      {
        path: 'home',
        name: 'Home',
        component: () => import('../views/common/Home.vue'),
        meta: { requiresAuth: true }
      },
      {
        path: 'users',
        name: 'Users',
        component: () => import('../views/admin/Users.vue'),
        meta: { requiresAuth: true }
      },
      {
        path: 'colleges',
        name: 'Colleges',
        component: () => import('../views/admin/Colleges.vue'),
        meta: { requiresAuth: true }
      },
      {
        path: 'majors',
        name: 'Majors',
        component: () => import('../views/admin/Majors.vue'),
        meta: { requiresAuth: true }
      },
      {
        path: 'classes',
        name: 'Classes',
        component: () => import('../views/admin/Classes.vue'),
        meta: { requiresAuth: true }
      },
      {
        path: 'courses',
        name: 'Courses',
        component: () => import('../views/teacher/Courses.vue'),
        meta: { requiresAuth: true }
      },
      {
        path: 'course-selection',
        name: 'CourseSelection',
        component: () => import('../views/student/CourseSelection.vue'),
        meta: { requiresAuth: true }
      },
      {
        path: 'questions',
        name: 'Questions',
        component: () => import('../views/teacher/Questions.vue'),
        meta: { requiresAuth: true }
      },
      {
        path: 'papers',
        name: 'Papers',
        component: () => import('../views/teacher/Papers.vue'),
        meta: { requiresAuth: true }
      },
      {
        path: 'exam-management',
        name: 'ExamManagement',
        component: () => import('../views/teacher/ExamManagement.vue'),
        meta: { requiresAuth: true }
      },
      {
        path: 'grading-list',
        name: 'GradingList',
        component: () => import('../views/teacher/GradingList.vue'),
        meta: { requiresAuth: true }
      },
      {
        path: 'grading/:examId',
        name: 'Grading',
        component: () => import('../views/teacher/Grading.vue'),
        meta: { requiresAuth: true }
      },
      {
        path: 'student-exam-records',
        name: 'StudentExamRecords',
        component: () => import('../views/teacher/StudentExamRecords.vue'),
        meta: { requiresAuth: true }
      },
      {
        path: 'score-statistics',
        name: 'ScoreStatistics',
        component: () => import('../views/teacher/ScoreStatistics.vue'),
        meta: { requiresAuth: true }
      },
      {
        path: 'exams',
        name: 'ExamList',
        component: () => import('../views/student/ExamList.vue'),
        meta: { requiresAuth: true }
      },
      {
        path: 'my-scores',
        name: 'MyScores',
        component: () => import('../views/student/MyScores.vue'),
        meta: { requiresAuth: true }
      },
      {
        path: 'exam-taking/:paperId?/:examId?',
        name: 'ExamTaking',
        component: () => import('../views/student/ExamTaking.vue'),
        meta: { requiresAuth: true }
      },
      {
        path: 'exam-result/:examId',
        name: 'ExamResult',
        component: () => import('../views/student/ExamResult.vue'),
        meta: { requiresAuth: true }
      },
      {
        path: 'exam-records/:paperId',
        name: 'ExamRecords',
        component: () => import('../views/teacher/ExamRecords.vue'),
        meta: { requiresAuth: true }
      }
    ]
  },
  {
    path: '/:pathMatch(.*)*',
    redirect: '/home',
    meta: { requiresAuth: false }
  }
]

const router = createRouter({
  history: createWebHistory(),
  routes
})

// 路由守卫 - 从localStorage检查登录状态
let isNavigating = false // 防止循环导航的标志

// 验证token是否有效（检查用户信息是否完整）
function isValidLogin(): boolean {
  const token = localStorage.getItem('token')
  const userId = localStorage.getItem('userId')
  const username = localStorage.getItem('username')
  const roleType = localStorage.getItem('roleType')
  
  // 如果token存在但用户信息不完整，则认为登录无效
  if (token && (!userId || !username || !roleType)) {
    // 清除无效的登录信息
    localStorage.removeItem('token')
    localStorage.removeItem('userId')
    localStorage.removeItem('username')
    localStorage.removeItem('roleType')
    return false
  }
  
  return !!token
}

router.beforeEach((to, from, next) => {
  // 如果正在导航中，直接放行，避免循环
  if (isNavigating) {
    next()
    return
  }
  
  // 检查登录状态（验证token和用户信息是否完整）
  const isLoggedIn = isValidLogin()
  
  // 从路由匹配记录中获取meta信息（支持嵌套路由）
  const requiresAuth = to.matched.some(record => record.meta?.requiresAuth === true)
  
  // 如果已经在目标页面，直接放行
  if (to.path === from.path) {
    next()
    return
  }
  
  // 需要登录但未登录
  if (requiresAuth && !isLoggedIn) {
    if (to.path !== '/login') {
      isNavigating = true
      next('/login')
      setTimeout(() => { isNavigating = false }, 100)
    } else {
      next()
    }
    return
  }
  
  // 已登录，访问登录/注册页，重定向到首页
  if ((to.path === '/login' || to.path === '/register') && isLoggedIn) {
    isNavigating = true
    next('/home')
    setTimeout(() => { isNavigating = false }, 100)
    return
  }
  
  // 正常放行
  next()
})

export default router